import React, { useEffect } from 'react'
import { AutoComplete } from './autoComplete'
import classnames from 'classnames'

export const SimpleSelector = ({ placeholder = '', inputClassName, dataSource, initValue,
    onSelectItem, getItemValue, renderItem, filterDataSource, readOnly, onClickQuickEdit }) => {
    const [filteredDataSource, setFilteredDataSource] = React.useState(dataSource)
    const [value, setValue] = React.useState(initValue)

    const onChangeTextHandler = React.useCallback(ev => {
        const value = ev.target.value
        setValue(value)
        setFilteredDataSource(dataSource.filter(filterDataSource(value)))
    }, [dataSource])

    const wrapOnSelectItem = React.useCallback(item => {
        const value = getItemValue(item)
        setValue(value)
        onSelectItem(item)
        setFilteredDataSource(dataSource)
    }, [dataSource, onSelectItem, getItemValue])

    useEffect(() => setValue(initValue), [initValue])
    useEffect(() => setFilteredDataSource(dataSource), [dataSource])

    return (
        <AutoComplete inputClassName={classnames(inputClassName, { empty_value: !value })}
            renderItem={renderItem} dataSource={filteredDataSource}
            onChangeText={onChangeTextHandler} onSelectItem={wrapOnSelectItem}
            value={value} getValue={getItemValue} readOnly={readOnly}
            placeholder={placeholder} onClickQuickEdit={onClickQuickEdit} />
    )
}